/*
 * FeedRepresentation.java
 *
 * Created on March 27, 2007, 11:55 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.app;

import java.net.URI;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import org.atomojo.app.db.Feed;
import org.restlet.data.Form;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.ServerResource;

/**
 *
 * @author alex
 */
public class QueryResource extends ServerResource {

   static final URI CHILD_TERM = URI.create("http://www.atomojo.org/O/relations/child");
   static final URI ANCESTOR_TERM = URI.create("http://www.atomojo.org/O/relations/ancestor");
   Reference resourceBase;
   Storage storage;
   App app;
   Feed feed;
   QueryFinder.QuerySpec spec;
   
   /** Creates a new instance of FeedRepresentation */
   public QueryResource(Reference resourceBase,App app,Storage storage,Feed feed,QueryFinder.QuerySpec spec) {
      setNegotiated(false);
      this.resourceBase = resourceBase;
      this.app = app;
      this.storage = storage;
      this.feed = feed;
      this.spec = spec;
   }
   
   public Representation get() {
      try {
         Form parameters = getRequest().getResourceRef().getQueryAsForm();
         Map<String,String> queryParameters = null;
         if (parameters!=null && parameters.size()>0) {
            queryParameters = new TreeMap<String,String>();
            for (String name : parameters.getNames()) {
               queryParameters.put(name,parameters.getValues(name));
            }
         }
         Representation rep = spec.useCollection() ? 
            storage.queryCollection(feed.getPath(),feed.getUUID(),spec.getQuery(),queryParameters) :
            storage.queryFeed(feed.getPath(),feed.getUUID(),spec.getQuery(),queryParameters);
         rep.setMediaType(spec.getMediaType());
         return rep;
      } catch (Exception ex) {
         getContext().getLogger().log(Level.SEVERE,"Cannot query feed "+feed.getUUID(),ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return null;
      }
   }
   
}
